# Treatment assignment variable -------------------------------------------

# The following code needs to be run on R version 3.5.3. or older
# It was used to produce 1000 vectors that contain the integers from 1 to 11 in random order

# seeds <- 1:1000
# 
# assign_videos <- function(seed){
# 	set.seed(seed)
# 	sample(1:11)
# }
# 
# assignments <- lapply(X = seeds, FUN = assign_videos)
# 
# save(assignments, file = "01_data/lab_experiment/LabAssignments.RData")

# Load the 1000 possible random assignments for all seeds between 1 and 1000
load("01_data/lab_experiment/LabAssignments.RData")

# The variable randomization_ID stores the seed that was used to generate the random assignment vector that a particular enumerator used 
# Enumerators had to enter the randomization_ID at the beginning of the interview
# Enumerator 11 uses randomization IDs 86 and 87 and then has 11 interviews done afterwards where 
# the randomization ID is NA but the treatment assignments correspond to a seed of 88

lab$randomization_ID[lab$enum == 11 &  is.na(lab$randomization_ID)] <- 88

lab <- lab[order(lab$enum, lab$starttime), ]

enum_data <- lab %>% 
	group_by(enum) %>%
	dplyr::summarize(n_interviews = n(),
									 n_seeds = ceiling(n_interviews/11),
									 start_seed = min(randomization_ID)) %>%
	ungroup() 

# Function to get the treatment assignment for each enumerator
getAssignments <- function(enumerator){
	result <-vector() 
	data <- enum_data %>% filter(enum == enumerator)
	for(i in 0:(data$n_seeds- 1)) {
		result <- c(result, assignments[[data$start_seed + i]])
	}
	result <- result[1:data$n_interviews]
}


# Get treatment assignment for each enumerator
lab$Z <- sapply(enum_data$enum, getAssignments) %>% unlist()

# Make binary version
lab$Z_absenteeism <- NA
lab$Z_absenteeism[lab$Z %in% c(1:10)] <- 0
lab$Z_absenteeism[lab$Z ==11] <- 1

rm(enum_data)
# Treatment received variable -------------------------------------------
lab$treatment_video <- NA
lab$treatment_video[lab$assignment_n == 1	] <- "C"
lab$treatment_video[lab$assignment_n == 2	] <- "CN"
lab$treatment_video[lab$assignment_n == 3	] <- "CS"
lab$treatment_video[lab$assignment_n == 4	] <- "E"
lab$treatment_video[lab$assignment_n == 5	] <- "EC"
lab$treatment_video[lab$assignment_n == 6	] <- "EN"
lab$treatment_video[lab$assignment_n == 7	] <- "ES"
lab$treatment_video[lab$assignment_n == 8	] <- "N"
lab$treatment_video[lab$assignment_n == 9	] <- "S"
lab$treatment_video[lab$assignment_n == 10]	<- "SN"
lab$treatment_video[lab$assignment_n == 11]	<- "T"

lab$absenteeism <- as.integer(lab$treatment_video=="T")




















